//
//  AFNetworkHandler.m
//  Project_B
//
//  Created by 张闯的mac pro on 15/11/23.
//  Copyright © 2015年 张闯. All rights reserved.
//

#import "AFNetworkHandler.h"
#import "AFNetworking.h"

@implementation AFNetworkHandler

+ (void)getUrl:(NSString *)url cookie:(NSString *)cookie result:(NETBLOCK)block
{
    NSString *newStr = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    //返回数据的格式
    [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"text/json", @"text/html", @"application/json",  @"text/plain", @"text/javascript", nil]];
    
    //接口带cookie
    //    [manager.requestSerializer setValue:cookie forHTTPHeaderField:@"Cookie"];
    
    [manager GET:newStr parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        
        //如果请求成功 回调请求数据后,同时在这里做本地缓存
        block(responseObject);
        // 本地缓存
        // 缓存的文件夹
        NSString *path = [NSString stringWithFormat:@"%ld.plist", [url hash]];
        // 存储的沙盒路径
        
        NSString *path_doc = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        // 归档
        [NSKeyedArchiver archiveRootObject:responseObject toFile:[path_doc stringByAppendingPathComponent:path]];
        
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        //在这里读取本地缓存
        NSLog(@"网络请求错误原因: %@", error);
        
        NSString *path = [NSString stringWithFormat:@"%ld.plist", [url hash]];
        NSString *path_doc = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        NSLog(@"%@", path_doc);
        id result = [NSKeyedUnarchiver unarchiveObjectWithFile:[path_doc stringByAppendingPathComponent:path]];
        block(result);
    }];
}

+ (void)requestPOSTWithURL:(NSString *)urlStr body:(NSData *)body comletion:(NETBLOCK)block
{
    /************异步POET网络请求************/
    
    NSString *newStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSURL *url = [NSURL URLWithString:newStr];
    
    if (!url) {
        NSString *path = [NSString stringWithFormat:@"%ld.plist", [url hash]];
        NSString *path_doc = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        id result = [NSKeyedUnarchiver unarchiveObjectWithFile:[path_doc stringByAppendingPathComponent:path]];
        block(result);
    }
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60];
    
    request.HTTPBody = body;
    
    request.HTTPMethod = @"POST";
    
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        
        // 本地缓存
        // 缓存的文件夹
        NSString *path = [NSString stringWithFormat:@"%ld.plist", [url hash]];
        // 存储的沙盒路径
        NSString *path_doc = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        // 归档
        
        [NSKeyedArchiver archiveRootObject:data toFile:[path_doc stringByAppendingPathComponent:path]];
        
        if (connectionError) {
            NSLog(@"网络请求错误: %@", connectionError);
            //            exit(0);
            
            NSString *path = [NSString stringWithFormat:@"%ld.plist", [url hash]];
            NSString *path_doc = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
            id result = [NSKeyedUnarchiver unarchiveObjectWithFile:[path_doc stringByAppendingPathComponent:path]];
            block(result);
            
            
        } else {
            
            
            NSError *error = nil;
            if (error) {
                NSLog(@"解析错误信息: %@", error);
                //            exit(0);
            } else {
                
                id resultEnd = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
                
                block(resultEnd);
            }
            
        }
        
    }];
    
}


+ (void)requestGETWithURL:(NSString *)urlStr comletion:(NETBLOCK)block
{
    //1.获取网址(传入的字符串:urlStr)
    //2.中文转码
    NSString *newStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    //3.string -> url
    NSURL *url = [NSURL URLWithString:newStr];
    //4.url -> request
    //参数一:网址
    //参数二:缓存机制
    //参数三:响应时间限制
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60];
    //5.建立连接
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        //6.判断网络请求是否成功
        if (connectionError) {
            NSLog(@"网络请求错误信息: %@", connectionError);
            //            exit(0);
        }
        
        //7.JSON解析
        NSError *error = nil;
        id resultEnd = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
        if (error) {
            NSLog(@"解析错误信息: %@", error);
            //            exit(0);
        }
        
        //8.通过BLOCK回调返回数据
        block(resultEnd);
        
    }];
}


//下载
+ (void)downloadFileURL:(NSString *)urString
{
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:config];
    
    NSString *string = urString;
    string = [string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSURL *url = [NSURL URLWithString:urString];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    NSURLSessionDownloadTask *task = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
        // 指定下载文件保存的路径
            NSLog(@"%@ %@", targetPath, response.suggestedFilename);
        // 将下载文件保存在缓存路径中
        NSString *cacheDir = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
        NSString *path = [cacheDir stringByAppendingPathComponent:response.suggestedFilename];
        NSLog(@"%@", path);
        
        // URLWithString返回的是网络的URL,如果使用本地URL,需要注意
        NSURL *fileURL1 = [NSURL URLWithString:path];
        NSURL *fileURL = [NSURL fileURLWithPath:path];
        
        NSLog(@"== %@ |||| %@", fileURL1, fileURL);
        
        return fileURL1;
    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
        NSLog(@"%@ %@", filePath, error);
    }];
    
    [task resume];
}




@end
